<?php

/**
*通过phpmailer发送邮件
*@author lssbing
* 
*/
if(!class_exists('BUY')) {
	require_once("BUY.class.php");
}
require_once(INC_PATH."/phpmailer/class.phpmailer.php");
require_once(INC_PATH."/phpmailer/class.smtp.php");
require_once(INC_PATH."/email_log.class.php");

/*
 * @return PHPMailer
 * 
 */ 
$mailobj = new PHPMailer();

class SendEmail {
	var $db;
	var $table;
	var $smtptable;
	var $sleeping_file;
	var $sleeping_time = 1800;
	var $file_append=1;
	var $errorMsg="";
	var $currTime;
	var $unuseMails=array();
	var $smtparray=array();
	var $smtpcount=0;
	var $printmsg="";
	var $mailobj;
	function __construct()
	{
		global $db,$tablepre,$timestamp,$mailobj;
		$this->db=$db;
		$this->sleeping_file=DATA_CACHEPATH."/sleepMail.dat";//休眠email存储地址
		$this->currTime=$timestamp;
		$this->table=$tablepre."email";
		$this->smtptable=$tablepre."smtpaccount";
		$this->setsmtp();
		$this->getsleepmail();
		$this->mailobj = $mailobj;
	}
	function SendEmail(){
		$this->__construct();
	}
	//执行发送
	function run($subject,$body,$emailarray){
		if(is_array($emailarray)){
			foreach ($emailarray as $value){
				$this->sendmailto($subject,$body,$value['email']);
			}
		}else $this->printmsg="数据格式错误";
	}
	//发送操作
	function sendmailto($subject,$body,$to){
		$errorNo=0;
		$subject = $subject ? $subject : "";
		$mailbody = $body ? $body : "" ;
		$to = $to ? $to : "" ;
//		do {
//			$rnd = mt_rand(0, $this->smtpcount - 1);
//			$line = is_array($this->smtparray[$rnd]) ? $this->smtparray[$rnd] : "";
//		}while (in_array($line['smtp_account'], $this->unuseMails));//如果在不可用的列表中，在次加载
//		$smtpServer = $line['smtp_server'];
//        $fromMail = $line['smtp_account'];
//        $psw = $line['smtp_password'];
//        $port = $line['smtp_port'];
//        $auth=$line['smtp_auth'];
//        $reply=$line['reply_address'];
//        $ssl=$line['smtp_ssl'];
//        $name=$line['smtp_name'];
//        $smtpUserName = substr($fromMail, 0, strrpos($fromMail, '@'));
        
//		if (!isset($smtpServer) || !isset($fromMail) || !isset($psw)) {
//	       	$errorNo = 2;
//	        $this->errorMsg = "没找到发件人信息";
//		}
		if (empty($mailbody) || empty($subject) || empty($to)) {
		    $errorNo = 1;
		    $this->errorMsg = "參數不全!";
		}
		if (!$errorNo) {
			//处理发信操作
			//通过phpmailer连接smtp服务器发信
			
			$this->mailobj->ClearAddresses();	//清除上次设置的发送地址
			$this->mailobj->ClearAttachments(); //清除上次设置的附件信息
			$this->mailobj->ClearReplyTos(); 	//清除回复人设置
			
		    $body = eregi_replace("[\]",'',$mailbody); //去掉反斜杠
		    
			$subject= $smtpUserName.$subject; //设置标题自动变
			
		    $this->mailobj->CharSet = "utf-8";
		    $this->mailobj->SetLanguage('zh');//设置语言为繁體中文
		    $this->mailobj->IsSMTP(); 
//		    if($auth)$this->mailobj->SMTPAuth = true;else $this->mailobj->SMTPAuth = false;
 			$this->mailobj->SMTPAuth   = true;//修改過
//		    if($ssl)$this->mailobj->SMTPSecure = "ssl";else $this->mailobj->SMTPSecure = "";
			$this->mailobj->SMTPSecure = "";
		   	$this->mailobj->Port       = 25;//设置端口
		   	$this->mailobj->Username = "squall@buy917.com"; //
		   	$this->mailobj->Password = "au061o4"; //
		   	
//			if ("smtp.qq.com" == trim($smtpServer)) {
//		        $this->mailobj->Username = $fromMail;
//		    } else {
//		        $this->mailobj->Username = $smtpUserName;
//		    }
			$this->mailobj->Host = "mx.buy917.com";//修改過
			$this->mailobj->From = "MailSender@buy917.com";//修改過
			$this->mailobj->FromName = "Buy917團購網";//修改過
			$this->mailobj->IsHTML(true);
			$this->mailobj->AddAddress($to);
			$this->mailobj->AddReplyTo("MailSender@buy917.com" , "MailSender");//修改過
			$this->mailobj->Subject = $subject;
//			$this->mailobj->Body = $body;
			$this->mailobj->MsgHTML($body);//修改過
			
			$email_log = new EmailLogClass();//紀錄email發送log
			
			if (!$this->mailobj->Send()) {
				$errorNo = 3;
				$this->errorMsg = $this->mailobj->ErrorInfo;
//				$this->printmsg.= "出錯 ($this->errorNo) " . $this->errorMsg . " |<Br/>";
				$this->printmsg.= "發送到 $to 出錯 XXXXXXXXX<Br/>";
				$email_log->add($to,0);//log to email_log  發送失敗
			} else {
//				$this->printmsg.= "發送到 $to 成功使用 $fromMail <Br/>";
				$this->printmsg.= "發送到 $to 成功<Br/>";
				$email_log->add($to,1);//log to email_log  發送成功
				sleep(1);//休眠5秒钟再发
				
			}
		}
		if ($errorNo == 3) {
		    $content = "MailSender@buy917.com|" . time() . "\r\n";//email|当前时间戳
		    file_put_contents($this->sleeping_file, $content, 1);
		}
		
	}
	
	//获取休眠状态email
	function getsleepmail(){
	    if (file_exists($this->sleeping_file)) {
        $sleepMails = file($this->sleeping_file);
        if (!empty($sleepMails)) {
            foreach($sleepMails as $sleepMail) {
                //解析
                if (false !== strpos($sleepMail, '|')) {
                    $tmp = explode('|', $sleepMail);
                    if (isset($tmp[0]) && isset($tmp[1])) {
                        $mail = trim($tmp[0]);
                        $time = trim($tmp[1]);
                        //是否可用
                        	if ( ($currTime - $time )< $this->sleeping_time) {
                            	$this->unuseMails[] = $mail;
                       		}
	                   	}
                	}
            	}
	       	}
    	}
	}
	function setsmtp(){
		include_once(INC_PATH."/smtpaccount.class.php");
		$smtp=new SmtpaccountClass();
		//设置总数和数组
		$this->smtpcount=$smtp->getcount("state=1"); 	
		$this->smtparray=$smtp->getdata("","state=1");//查询获取数据
		unset($smtp);
	}
	
	/*
	 * 購買成功發信給消費者
	 */
	function sendOrderSuccessMail($order_id ){
		$orderObj = BUY::getOrder();
		$order = $orderObj->getone($order_id);
		$member = BUY::getMember()->getone($order['uid']);
		$subject = "Buy917團購網-購買成功:".mb_strimwidth($order["gtitle"],0,100,"...","UTF-8");
		$to = $member['email'];
		$body = '
		<p>親愛的  <strong  style="color: #00F;">'.$member['uname'].'</strong> 您好： </p>
		<p>感謝參與這次的購買 :</p>
		<h2>
			<a href="http://www.buy917.com/view.php?gid='.$order['gid'].'" target="_blank">
			'.$order['gtitle'].'
			</a>				
		</h2>
		<p>若要列印團購卷請至 <a href="http://www.buy917.com" target="_blank">《Buy917團購網首頁》</a> -&gt; 《登入會員》 -&gt; <a href="http://www.buy917.com/m.php?action=bond" target="_blank">《我的團購卷》</a> 。</p>
		<p>記得每天回來 《<a href="http://www.buy917.com" target="_blank">Buy917團購網</a> 》 看看最新優惠喔。<br />
		  客服專線：  02-22680329 週一 ~ 週五 早上9點 ~ 下午 6點<br />
		  本內容由系統自動發送，如有問題請來信 <a href="mailto:service@buy917.com">service@buy917.com </a>，請勿回覆本信。<br />
		© 版權 2010-2011 版權所有 歐映有限公司</p>
		';
		$this->sendmailto($subject , $body , $to);
	}
	
}

?>